package com.knight.server;

import com.knight.service.impl.OrderServiceImpl;
import com.knight.spring.RpcService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class RPCServer implements ApplicationContextAware, InitializingBean{


    private Map<String,Object> handlers = new HashMap<>();

    public void read(){
        ObjectInputStream objectInputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            ServerSocket serverSocket = new ServerSocket(8080);
            System.out.println("knight RPC server start up");
            while (true) {
                Socket socket = serverSocket.accept();
                new Processor(handlers,socket.getInputStream(),socket.getOutputStream()).start();
            }


        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(RpcService.class);
        if (beansWithAnnotation!=null) {
            beansWithAnnotation.forEach((k,v)->{
                String className = v.getClass().getAnnotation(RpcService.class).value().getName();
                handlers.put(className,v);
            });
        }
    }

    /**
     * 在执行bean的init方法中执行
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        read();
    }
}
